package pri.zey.custom.tools;/**
 * Created by Administrator on 2016/3/16.
 */

import android.util.Log;

import java.security.MessageDigest;

/**
 * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>类描述
 * 编码工具
 * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>属性描述
 * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>方法描述
 */
public class TEncode {

    private final String TAG = "TEncode";

    /**
     * SHA1加密
     */
    public String endecodeSHA1(String token, String nonce, String timestemp){
        String tempStr = token + timestemp + nonce;
        tempStr = encodePassword(tempStr, "sha-1");
        return tempStr;
    }

    /**
     * 随机生成8位密码
     *
     * @param length
     * @return
     */
    public String generatePassword(int length) {
        java.util.Random r = new java.util.Random();
        StringBuilder sb = new StringBuilder();
        if (length <= 0) {
            length = 6;
        }
        for (int i = 0; i < length; i++) {
            sb.append(Integer.toString(r.nextInt(36), 36));
        }
        return sb.toString();
    }

    public String getRandom(int length) {

        return "";
    }

    /**
     * 用指定的加密算法加密
     *
     * @param password  Password or other credentials to use in authenticating this username
     * @param algorithm Algorithm used to do the digest
     * @return encypted password based on the algorithm.
     */
    public String encodePassword(String password, String algorithm) {
        String encypted = "";
        byte[] unencodedPassword = password.getBytes();

        MessageDigest md;

        try {
            // first create an instance, given the provider
            md = MessageDigest.getInstance(algorithm);
        } catch (Exception e) {
            Log.i(TAG, "Exception: " + e);
            return password;
        }

        md.reset();

        // call the update method one or more times
        // (useful when you don't know the size of your data, eg. stream)
        md.update(unencodedPassword);

        // now calculate the hash
        byte[] encodedPassword = md.digest();

        StringBuffer buf = new StringBuffer();

        for (int i = 0; i < encodedPassword.length; i++) {
            if ((encodedPassword[i] & 0xff) < 0x10) {
                buf.append("0");
            }

            buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
        }
        encypted = buf.toString().toLowerCase();
        return encypted;
    }
}
